RAILS_ENV = 'development'
require File.dirname(__FILE__) + "/../../config/environment"
require 'jcode'
$KCODE = 'u'

require 'lrs/utils'

class DebateAnalyser
  include Utils
  
  def initialize(sit)
    @sitting = sit
  end
  
  def analyse(url)
    doc = utf_page url
    (doc/"p.Roman").each do |el|
      line = el.inner_text
      m = line.match(/^\D\.(\D\.)?\w+/)
      if m then
        speeker = m.to_s.split('.')
        speeker_first_name_initial = speeker.first
        speeker_last_name = capitalize_name(speeker.last)
        author_sql =<<-SQL
        select * from politicians
        where
          last_name = '#{speeker_last_name}' and
          (substring(first_name, 1,1) = '#{speeker_first_name_initial}' or substring(second_name, 1,1) = '#{speeker_first_name_initial}')
        SQL
        mp_speeker = Politician.find_by_sql(author_sql).first
        if mp_speeker then
          speech = line.sub m.to_s, ''
          speech.scan( /( \D\.(\D\.)?\w+)/ ).each do |mp|
            name = strip_last_name mp[0].strip
            first_name_initials = name.split('.').first
            last_name = name.split('.').last
            reference_sql=<<-SQL
            select * from politicians
            where
              last_name like '#{last_name + '%'}' and
              (substring(first_name, 1,1) = '#{first_name_initials}' or substring(second_name, 1,1) = '#{first_name_initials}')
            SQL
            ref_mp = Politician.find_by_sql(reference_sql).first
            mp_speeker.debate_references << 
              mp_speeker.debate_references.new(:name_reference_id => ref_mp.id, :sitting_id=>@sitting.id) if ref_mp 
          end
          mp_speeker.save
        end
      end
    end
  end
  
  
  private
  
  def strip_last_name(name)
    name.gsub(/(ai|as|ą|čiui|čio|is|io|į|iuj|iu|iaus|iui|ius|ių|iumi|os|iaus|o|u|ui|ys)$/, '').gsub(/(|ė|ės|ei|e|ę|a)$/, '')
  end

  def capitalize_name(name)
    c_name = ''
    index = 1
    name.each_char{ |char|
      n =  index == 1 ? char : char.downcase.tr("ĄČĘĖĮŠŲŪŽ","ąčęėįšųūž")
      c_name += n
      index += 1
    }
    c_name
  end
end
=begin
Test selektas
select src.last_name as a, ref.last_name as b
from debate_references, politicians as src, politicians as ref
where debate_references.politician_id = src.id and
debate_references.name_reference_id = ref.id
=end
#DebateReference.delete_all
#DebateAnalyser.new.analyse 'http://www3.lrs.lt/pls/inter3/dokpaieska.showdoc_l?p_id=324770'
